package com.guozcc.bootweb.api.exception;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * API统一异常处理
 */
@Slf4j
@ControllerAdvice(basePackages = "com.guozcc.bootweb.api")
public class GlobalApiExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public JSONObject globalException(HttpServletResponse response, Exception ex)  {
        log.error("",ex);
        JSONObject exceptionException = new JSONObject(){{
            put("ec","9999");
            put("em","异常exception:");
        }};
//        response.getOutputStream().write(exceptionException.toJSONString().getBytes("UTF-8"));
        return exceptionException;
    }

    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public void globalException(HttpServletResponse response, NullPointerException ex)  {
        log.error("",ex);
        JSONObject exceptionException = new JSONObject(){{
            put("ec","9999");
            put("em","异常NullPointerException:");
        }};
        try{
            response.getOutputStream().write(exceptionException.toJSONString().getBytes("UTF-8"));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
